Published in:2024-10-24 |

字符串

一、字符串简介

字符串是编程世界中最常用的一个数据类型,它表示一个文本,例如表示一个人的名字”Mr_lee”。

在Python字符串需要使用引号来包围。可以是单引号、双引号或三引号

1
2
3
4
5
6
7
8
9
10
# 单引号、双引号用来表示单行字符串   s = "Tom\nJack" print(s)
s1 = 'Tom'
s2 = "Tom"

# 三引号一般用来表示多行字符串
s3 = '''Tom'''
s4 = """
Tom
Jack
"""
  • 字符串的特点:

    • 具有天生的跨平台的特性(C、C++、Java…)
    • 是一个序列(有序的数列)
    • 支持下标操作
    • 支持切片
    • 可迭代对象
    • 不可变类型 s = 'abc' s= 'Tom' 并不是修改了内容而是修改了指向
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    s = "String"
    print(s)
    s[3] = 'o' # 不可修改内容 Error
    print(s)
    s = "Strong"
    print(s) # 改变指向


    a = 5
    print(id(a)) # 1871015072
    a = 10
    print(id(a)) # 1871015232 # 指向发生了改变


    a = [1,2]
    print(id(a)) # 41174664
    a[0] = 10 # 修改列表的内容-元素 列表的指向并没有发生改变
    print(id(a)) # 41174664
  • Python中的字符串与C、C++的不同之处:

    • Python没有单字符,所有的单字符也是当作字符串进行处理

      s = 'a' s = "a" 它们都是字符串 类型都是str

    • 而C、C++中 ‘’表示的为单字符,而“”表示的为字符串

      char s = 'A' string s = "ABC" 类型不一样

二、字符串的创建

  • 直接创建

    1
    2
    s = 'abc'
    print(s) # 大多数情况下使用
  • 工厂函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    s1 = str()
    print(s1) # -> '' 空字符串 长度为0

    s2 = str(' ')
    print(s2) # 空格 长度为1

    s3 = str(123)
    print(s3) # 将int 转为 字符串str

    s4 = str(123.4) # -> '123.4' 字符串在使用print输出时,不会显示引号
    s5 = str(True) # -> 'True'
    s6 = str(None) # -> 'None'
    s7 = str([1,2,3]) # -> '[1,2,3]'
    # 补充: eval()
    # print(eval("1+2")) -> 3 eval("[1,2,3,4]") -> [1,2,3,4]

三、字符串的访问

可以通过下标或切片来获取字符串中的内容

1
2
3
4
5
6
7
s = 'Hello World'
print(s[0])
print(s[:])
print(s[1:])

for i in s:
print(i,end=',') # H,e,l,l.....

四、字符串运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1. +  实现字符串的拼接
s1 = 'Hello'
s2 = 'world'
s3 = s1 + s2 # 'Helloworld'
# 字符串不能和整数直接相加

2. * 实现字符串重复
s1 = '*'
s2 = '*' * 3
print(s2) # '***'

3. in/not in 判断是否存在
s = 'HelloWorld'
print('l' in s) # True
print('ll' in s) # True

4. r/R
print("ABC\nDEF") # ABC 这里会换行 DEF
print(r"ABC\nDEF") # ABC\nDEF 原样输出 输出原始字符串

五、字符串中的方法

  • 大小写转换

    • s.capitalize() : 将首字母转为大写

      1
      2
      3
      s = 'helloworld'
      print(s.capitalize()) # -> Helloworld 转换后生成新的字符串
      print(s) # -> helloworld 原字符串不变
    • s.lower(): 将字符串转为小写

      1
      print("HelloWorld".lower())  # -> helloworld
    • s.upper():将字符串转为大写

      1
      print("helloworld".upper())  # -> HELLOWORLD
    • s.swapcase():翻转大小写

      1
      print("HelloWorld".swapcase())  # -> hELLOwORLD
    • s.title() :标题化字符串,将所有单词的首字母转为大写,其余的小写

      1
      print("hello world".title())  # -> Hello World
    • s.casefold() : 全部转为小写 – 类似于lower() 功能比lower更强大

      1
      2
      print("ΕΖΗ".lower())   # εζη
      print("ΕΖΗ".casefold()) # εζη
  • 字符串样式

    • s.center(width[,fillchar]) 返回一个字符串居中,并使用空格来填充至长度为width的新字符串,fillchar为可选参数,表示要填充的内容

      1
      2
      3
      s = "helloworld"
      print(s.center(20)) # -> ' helloworld '
      print(s.center(20,'*')) # -> '*****helloworld*****'
    • s.ljust(width[,fillchar]) :返回一个字符串左对齐,使用空格填充至长度为width的新字符串

      1
      2
      3
      s = "helloworld"
      print(s.ljust(20)) # -> 'helloworld '
      print(s.ljust(20,'*')) # -> 'helloworld**********'
    • s.rjust(width[,fillchar]) :返回一个字符串右对齐,使用空格填充至长度为width的新字符串

      1
      2
      3
      s = "helloworld"
      print(s.rjust(20)) # -> ' helloworld'
      print(s.rjust(20,'*')) # -> '**********helloworld'
    • s.zfill(width): 返回一个长度为width的字符串,右对齐,前面使用0填充

      1
      2
      s = "helloworld"
      print(s.zfill(20)) # -> 0000000000helloworld
    • s.expandtabs():设置制表符的长度 默认为8

      1
      2
      s = "hello\tworld\ta\tb"
      print(s.expandtabs()) # hello world a b
  • 搜索字符串

    • s.count(sub[,start[,end]]) :在指定范围内查找子串的个数

      1
      2
      3
      4
      5
      s = "helloworld"
      print(s.count('l')) # -> 3
      print(s.count('lo')) # -> 1
      print(s.count('l',5)) # -> 1
      print(s.count('l',1,5)) # -> 2
    • s.find(sub[,start[,end]]) 在指定范围内查找第一个子串的位置,未找到则返回-1

      1
      2
      3
      4
      5
      s = "helloworld"
      print(s.find('l')) # -> 2
      print(s.find('L')) # -> -1
      print(s.find('l',5)) # -> 8
      print(s.find('l',2,5)) # -> 2
    • s.index(sub[,start[,end]]) 在指定范围内查找子串的位置,未找到时报错

      1
      2
      3
      s = "helloworld"
      print(s.index('l'))
      print(s.index('L')) # ValueError: substring not found
  • 替换字符串

    • s.replace(old,new[,count]) 使用new来替换old子串,count用于指定要替换的个数,默认替换所有

      1
      2
      3
      4
      s = "helloworld"
      print(s.replace('l','a')) # -> heaaoworad
      print(s.replace('l','a',1)) # -> healoworld
      print("a,b,c,d,e".replace(',','')) # abcde
    • s.strip([chars]):删除字符串两边的字符,默认是空格

      1
      2
      3
      4
      5
      s = "  Tom  "
      print(s.strip()) # -> 'Tom'

      s = '**Tom**'
      print(s.strip('*')) # -> 'Tom'
    • s.lstrip([chars]) / s.rstrip([chars]) : 删除左边 或 删除右边的空格或指定的字符

      1
      2
      3
      4
      5
      s = "  Tom  "
      print(s.lstrip()) # -> 'Tom '

      s = '**Tom**'
      print(s.lstrip('*')) # -> 'Tom**'
  • 字符串联合

    • s.join(iterable) : 使用s来连接可迭代对象生成新的字符串

      1
      print("-".join("abc"))
  • 字符串分隔

    • s.split(sep,max=-1) 用指定的字符来对原字符串进行分隔
    1
    2
    3
    s = "hello world haha"
    print(s.split()) # ['hello', 'world', 'haha'] # 默认以空格分隔
    print(s.split(" ",1)) # ['hello', 'world haha']
  • 判断前缀和后缀

    • s.startswith(prefix) 判断某个字符串是否有某个前缀
    1
    2
    s = "http://www.baidu.com"
    print(s.startswith('http'))
    • s.endswith(suffix[start,[stop]]) 判断是否有某个后缀
    1
    2
    s = "http://www.baidu.com"
    print(s.endswith('.com'))
  • 判断是否是某种类型

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    # 1. isalpha()  所有字符是否都为字母    
    s = "abc"
    print(s.isalpha()) # True

    s = "123"
    print(s.isalpha()) # False

    s = "abc123"
    print(s.isalpha()) # False

    # 2. isalnum() 是否都为字母或数字组成
    print("abc123".isalnum()) # True
    print("abc".isalnum()) # True
    print("123".isalnum()) # True
    print("123,".isalnum()) # False


    # 3. isdigit() 是否为数字 0-9
    print("abc".isdigit()) # False
    print("123".isdigit()) # True
    print("123.123".isdigit()) # False 0-9
    print("abc123".isdigit()) # False

    # 4. isnumeric() 是否为数字 功能比isdigit强大 计数字符
    print("⑵".isnumeric()) # True
    print("123".isnumeric()) # True
    print("壹".isnumeric()) # True
    print("Ⅱ".isnumeric()) # True
    print("壹".isdigit()) # False

    # 5. isspace() 是否全为空格
    print(" ".isspace())

    # 6. islower() / isupper() 是否全为小写或大写
    print("abc".islower()) # True
    print("ABC".islower()) # False
    print("ABC".isupper()) # True
    print("abc".isupper()) # False

    # 7. isdecimal() 是否为十进制的数
    print("123".isdecimal()) # True

六、字符串的格式化

在程序中,可能需要得到或输出这样的一个字符串“亲爱的xxx用户你好!你xx月的话费是x”

1
2
3
4
5
a = "中国联通"
month = 6
money = 128
print("亲爱的"+a+"用户你好!你"+str(month)+"月的话费是"+str(money))
# -> 亲爱的中国联通用户你好!你6月的话费是128

在Python中可以使用一种简便的格式化字符串的方式来将某些变量的值插入到固定格式的字符串。

1
2
3
4
5
a = "中国联通"
month = 6
money = 128
s = "亲爱的%s用户你好!你%d月的话费是%d"%(a,month,money)
print(s)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1. %d   格式化整数
2. %f 格式化小数
3. %s 格式字符串(也可以是其它类型)
4. %c 格式化字符或ASCII print("%c,,,,,,%c"%(65,66)) #-> A,,,,,,B
5. %e 科学计数法
print("a=%d"%123) # a=123
print("a=%e"%123) # a=1.230000e+02
6. %o 格式化八进制
print("%o"%10) # 12
print("%#o"%10) # 0o12
7. %x 格式化为十六进制
print("%o"%10) # 12
print("%#o"%10) # 0o12

print("%d"%0xf) # 将16进制的转为10进制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 特殊用法:
# .n 保留几位小数
# m.n 一共占几位
# - 左对齐
# 10d 数字占10位
# 010d 不够用0补

print("%f"%3.1415926535897)
print("%.2f"%3.1415926535897)
print("%10.2f"%3.1415926535897) # 一共占10位 不够用空格补 补前面 右对齐
print("%-10.2f"%3.1415926535897) # -号 左对齐

print("%10d"%3)

for i in range(20):
print("%2d"%i)

for i in range(20):
print("%02d" % i) # 位数不够用0补


for i in range(1,10):
for j in range(1,i+1):
print("%d * %d = %02d "%(j,i,i*j),end='')
print()
  • 另一种格式化方式: format

    • 形式: “{},{}”.format(参数1,参数2)
    • 使用{}来表示占位
    1
    2
    3
    4
    5
    6
    7
    8
    9
    a = 5
    b = 10
    c = 20
    print("a=%d,b=%d"%(a,b)) # 'a=5,b=10'
    print("a={},b={}".format(a,b))
    print("a={0},c={2},b={1}".format(a,b,c))

    # 关键字参数
    print("{url},{name}".format(name="Python教程",url="www.baizhiedu.cn"))
  • Python3.6之后,新加了一种格式化的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
a = 50
b = 10
print(f'{a}{b}') # 直接引用变量a和b
print(f'{a+b}')
print(f'{a//b}') # 参与运算

for i in range(1,10):
for j in range(1,i+1):
print(f'{j}*{i}={i*j:2d} ',end='')
print()

pi = 3.14159265397
print(f"{pi:.2f}")
Prev:
Next: